package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.UserSearchDto;
import com.heima.search.service.ArticleSearchService;
import io.micrometer.core.instrument.search.Search;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.util.QueryBuilder;
import org.checkerframework.checker.units.qual.A;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
   /*
   *
   * es文章分页检索
   * */
    @SneakyThrows
    @Override
    public ResponseResult search(UserSearchDto dto) {

        //检测参数
     if(dto==null&&dto.getSearchWords()==null){
         return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

     }
        SearchRequest appInfoArticle = new SearchRequest("app_info_article");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //设置查询条件

     //构建布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //关键字的分词之后查询
        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR);
         boolQueryBuilder.must(queryStringQueryBuilder);
        //查询小于mindate的数据
        RangeQueryBuilder publishTime = QueryBuilders.rangeQuery("publish_time").lt(dto.getMinBehotTime().getTime());
        boolQueryBuilder.filter(publishTime);
        //分页查询
         searchSourceBuilder.from(0);
         searchSourceBuilder.size(dto.getPageSize());
        //按照发布时间倒叙查询
       searchSourceBuilder.sort("publish_time", SortOrder.DESC);
        //设置高亮 高亮对象是title
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);


        searchSourceBuilder.query(boolQueryBuilder);
        appInfoArticle.source(searchSourceBuilder);

            SearchResponse searchResponse = restHighLevelClient.search(appInfoArticle, RequestOptions.DEFAULT);

        ArrayList<Map> list = new ArrayList<>();
        //结果封装返回
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            Map map = JSON.parseObject(sourceAsString, Map.class);

            //高亮处理
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null) {
                Text[] titles = highlightFields.get("title").getFragments();
                String title = StringUtils.join(titles);
                //高亮标题
                map.put("title", title);
            } else {

                map.put("title", map.get("title"));
            }
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }
}
